//
//  MSTextImage.m
//  Community
//
//  Created by luo danal on 3/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MSTextImage.h"
#import <QuartzCore/QuartzCore.h>

@implementation MSTextImage
@synthesize bgColor = _bgColor;
@synthesize titleColor = _titleColor;
@synthesize title = _title;
@synthesize hasCorners;
@synthesize image = _image;

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        CGRect rect = CGRectInset(self.bounds, 2.f, 2.f);
        _titleLabel = [[UILabel alloc] initWithFrame:rect];
        _titleLabel.font = [UIFont systemFontOfSize:12.f];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textAlignment = UITextAlignmentCenter;
        _titleLabel.adjustsFontSizeToFitWidth = YES;
        [self addSubview:_titleLabel];
        
        rect = CGRectMake(0, 0, frame.size.width, frame.size.height);
        _imageView = [[UIImageView alloc] initWithFrame:rect];
        [self addSubview:_imageView];
    }
    return self;
}

- (void)dealloc{
    [_titleColor release];
    [_bgColor release];
    [_title release];
    [_imageView release];
    [_image release];
    [super dealloc];
}

- (void)layoutSubviews{
    if (self.title != nil) {
        _titleLabel.text = self.title;
    }
    if (self.hasCorners == YES) {
        self.layer.cornerRadius = 4.f;
    }
    if (self.titleColor != nil) {
        _titleLabel.textColor = self.titleColor;
    }
    if (self.bgColor) {

        self.backgroundColor = self.bgColor;
//        _titleLabel.backgroundColor = self.bgColor;
    }
}

- (void)setImage:(UIImage *)image {
    if (_image != image) {
        [_image release];
        _image = [image retain];
        _imageView.image = _image;
    }
}


#pragma mark - Class methods

+ (MSTextImage *)imageWithFrame:(CGRect)frame 
                     title:(NSString *)title 
                titleColor:(UIColor *)color 
                   bgColor:(UIColor *)bgColor 
               withCorners:(BOOL)hasCorners 
{    
    MSTextImage *ti = [[[MSTextImage alloc] initWithFrame:frame] autorelease];
    ti.title = title;
    ti.titleColor = color;
    ti.bgColor = bgColor;
    ti.hasCorners = hasCorners;
    return ti;
}

+ (MSTextImage *)imageWithFrame:(CGRect)frame 
                        image:(UIImage *)image 
                  withCorners:(BOOL)hasCorners {
    MSTextImage *ti = [[[MSTextImage alloc] initWithFrame:frame] autorelease];
    ti.image = image;
    ti.hasCorners = hasCorners;
    return ti;    
}
@end
